package com.example.demo.filter;

import com.alibaba.fastjson.JSON;
import com.example.demo.domain.User;
import com.example.demo.untils.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    JwtConfig jwtConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token1 = request.getHeader("token");
        if(token1!=null) {
            Date issuedAtDateFromToken = jwtConfig.getExpirationDateFromToken(token1);
            boolean tokenExpired = jwtConfig.isTokenExpired(issuedAtDateFromToken);

            if(true) {
                String token = jwtConfig.getUsernameFromToken(token1);

                System.out.println(token);
                User parse = JSON.parseObject(token, User.class);
                //用缓存判断
                System.out.println(parse);
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(parse.getUserName(), parse.getPassword());
                SecurityContextHolder.getContext().setAuthentication(authRequest);
            }else {

            }
        }
        filterChain.doFilter(request,response);

    }
}
